package com.sneaker.shower.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sneaker.shower.entity.dto.KuaiDiResponse;
import com.sneaker.shower.service.KuaiDiService;
import com.sneaker.shower.service.SynQueryService;
import lombok.extern.slf4j.Slf4j;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Hechangjian
 * @version 1.0
 * @className KuaiDiService
 * @date 2019/09/01 14:09
 * @description a
 * @program bath
 */
@Slf4j
@Service
public class KuaiDiServiceImpl implements KuaiDiService {
    private SynQueryService synQueryService;
    private ObjectMapper objectMapper = new ObjectMapper();
    private ExpiringMap<String, KuaiDiResponse> expiringMap = ExpiringMap.builder().expiration(5, TimeUnit.MINUTES).expirationPolicy(ExpirationPolicy.CREATED).build();

    public KuaiDiServiceImpl(SynQueryService synQueryService) {
        this.synQueryService = synQueryService;
    }

    @Override
    public KuaiDiResponse findByNum(String number, String comCode) {
        try {
            KuaiDiResponse cache = expiringMap.get(number);
            if (cache != null) {
                return cache;
            }
            String string = synQueryService.synQueryData(comCode, number, "", "", "", 0);
            KuaiDiResponse response = objectMapper.readValue(string, KuaiDiResponse.class);
            expiringMap.put(number, response);
            return response;
        } catch (IOException e) {
            log.error("path fail:" + e);
            return null;
        }
    }
}
